/**
 * SysImageCtrl.java
 *
 */
package com.navidove.web.ctrl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.navidove.appspotlight.model.bo.SysImage;
import com.navidove.appspotlight.model.service.SysImageService;
import com.navidove.appspotlight.model.service.SysUserService;

/**
 * SysImageCtrl
 *
 * @author $Author$
 * @version $Revision$
 * @date $Date$
 * @url $URL$
 */
@Controller
public class SysImageCtrl {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysImageService sysImageService;

	@RequestMapping(value="/app/image/{imageId}")
	public void download(@PathVariable("imageId") Long imageId,
			HttpServletResponse response) {
		SysImage sysImage = sysImageService.getSysImage(imageId);

		String filename = sysImage.getFileName();
		try {
			filename = java.net.URLEncoder.encode(filename, "utf-8");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		String contentType = sysImage.getMime();
		long fileSize = sysImage.getFileSize();

		response.setContentType(contentType);
		response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
/*		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");*/
		response.setContentLength((int) fileSize);
		InputStream input = new ByteArrayInputStream(sysImage.getContent());
		try {
			IOUtils.copyLarge(input, response.getOutputStream());			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(input);
		}
	}	 
}
